<template>
  <div class="dictionary-manage-page">
    <!-- 固定头部 -->
    <div class="page-header-fixed">
      <div class="page-title">
        <h2>字典管理</h2>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="page-content">
      <div class="dictionary-container">
        <!-- 左侧：字典类型列表 -->
        <div class="dict-types-panel">
          <div class="panel-title">字典类型</div>
          <div class="type-list">
            <div
              v-for="type in dictTypes"
              :key="type.code"
              :class="['type-item', { active: selectedType === type.code }]"
              @click="handleSelectType(type.code)"
            >
              <component :is="type.icon" class="type-icon" />
              <div class="type-info">
                <div class="type-name">{{ type.name }}</div>
                <div class="type-count">{{ getTypeCount(type.code) }} 项</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：字典项管理 -->
        <div class="dict-items-panel">
          <div class="items-header">
            <div class="header-left">
              <h3>{{ currentTypeName }}</h3>
              <a-tag color="blue">共 {{ currentItems.length }} 项</a-tag>
            </div>
            <a-button
              type="primary"
              @click="handleAdd"
              v-permission="($route?.meta as any)?.$actions?.['create']?.code"
            >
              <template #icon><PlusOutlined /></template>
              添加字典项
            </a-button>
          </div>

          <a-table
            :columns="columns"
            :data-source="currentItems"
            :loading="loading"
            :pagination="false"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'dictLabel'">
                <span class="label-text">{{ record.dictLabel }}</span>
              </template>

              <template v-else-if="column.key === 'dictCode'">
                <a-tag color="default">{{ record.dictCode }}</a-tag>
              </template>

              <template v-else-if="column.key === 'isSystem'">
                <a-tag v-if="record.isSystem === 1" color="blue"
                  >系统字典</a-tag
                >
                <a-tag v-else color="default">自定义</a-tag>
              </template>

              <template v-if="column.key === 'status'">
                <a-switch
                  :checked="record.status === 1"
                  :disabled="record.isSystem === 1"
                  @change="(checked: boolean) => handleStatusChange(record, checked)"
                />
              </template>

              <template v-else-if="column.key === 'action'">
                <a-space :size="8">
                  <a-tooltip
                    v-if="record.isSystem === 1"
                    title="系统预置字典不可编辑"
                  >
                    <a-button type="link" size="small" disabled>
                      编辑
                    </a-button>
                  </a-tooltip>
                  <a-button
                    v-else
                    type="link"
                    size="small"
                    @click="handleEdit(record)"
                    v-permission="($route?.meta as any)?.$actions?.['edit']?.code"
                  >
                    编辑
                  </a-button>

                  <a-tooltip
                    v-if="record.isSystem === 1"
                    title="系统预置字典不可删除"
                  >
                    <a-button type="link" size="small" danger disabled>
                      删除
                    </a-button>
                  </a-tooltip>
                  <a-button
                    v-else
                    type="link"
                    size="small"
                    danger
                    @click="handleDelete(record)"
                    v-permission="($route?.meta as any)?.$actions?.['delete']?.code"
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </div>

    <!-- 添加/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="submitting"
      @ok="handleSubmit"
    >
      <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
        <a-form-item label="字典标签" name="dictLabel">
          <a-input
            v-model:value="formData.dictLabel"
            placeholder="请输入字典标签（中文显示名称）"
          />
        </a-form-item>

        <a-form-item label="排序" name="sortOrder">
          <a-input-number
            v-model:value="formData.sortOrder"
            :min="0"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item label="备注">
          <a-textarea
            v-model:value="formData.remark"
            :rows="3"
            placeholder="请输入备注信息（可选）"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { message, Modal } from "ant-design-vue";
import {
  PlusOutlined,
  DollarOutlined,
  CarOutlined,
  ToolOutlined,
  UserOutlined,
} from "@ant-design/icons-vue";
import {
  getAllDictionaries,
  addDictionary,
  updateDictionary,
  deleteDictionary,
} from "@/api/tenant/dictionary";
import type { Dictionary } from "@/types/dictionary";
import { clearDictionaryCache } from "@/composables/useDictionary";

// 字典类型配置
const dictTypes = [
  { code: "PAYMENT_METHOD", name: "付款方式", icon: DollarOutlined },
  { code: "VEHICLE_TYPE", name: "车辆类型", icon: CarOutlined },
  { code: "VEHICLE_STATUS", name: "车辆状态", icon: ToolOutlined },
  { code: "DRIVER_STATUS", name: "司机状态", icon: UserOutlined },
];

// 数据
const allDictionaries = ref<Dictionary[]>([]);
const loading = ref(false);
const selectedType = ref("PAYMENT_METHOD");

// 表格列
const columns = [
  { title: "字典标签", dataIndex: "dictLabel", key: "dictLabel", width: 150 },
  { title: "字典代码", dataIndex: "dictCode", key: "dictCode", width: 150 },
  { title: "类型", key: "isSystem", width: 100 },
  { title: "排序", dataIndex: "sortOrder", key: "sortOrder", width: 80 },
  { title: "状态", key: "status", width: 80 },
  { title: "备注", dataIndex: "remark", key: "remark", ellipsis: true },
  { title: "操作", key: "action", width: 150, fixed: "right" },
];

// 当前选中类型的字典项
const currentItems = computed(() => {
  return allDictionaries.value
    .filter((item) => item.dictType === selectedType.value)
    .sort((a, b) => a.sortOrder - b.sortOrder);
});

// 当前类型名称
const currentTypeName = computed(() => {
  return dictTypes.find((t) => t.code === selectedType.value)?.name || "";
});

// 获取某类型的数量
const getTypeCount = (typeCode: string) => {
  return allDictionaries.value.filter((item) => item.dictType === typeCode)
    .length;
};

// 切换字典类型
const handleSelectType = (typeCode: string) => {
  selectedType.value = typeCode;
};

// 加载所有字典
const loadDictionaries = async () => {
  loading.value = true;
  try {
    const response = await getAllDictionaries();
    allDictionaries.value = (response.data as any) || [];
  } catch (error) {
    message.error("加载字典失败");
  } finally {
    loading.value = false;
  }
};

// 弹窗相关
const modalVisible = ref(false);
const modalTitle = ref("");
const isEdit = ref(false);
const editingId = ref<number>();
const submitting = ref(false);
const formRef = ref();

const formData = reactive({
  dictCode: "",
  dictLabel: "",
  sortOrder: 0,
  remark: "",
});

const rules = {
  dictLabel: [{ required: true, message: "请输入字典标签" }],
  sortOrder: [{ required: true, message: "请输入排序" }],
};

// 重置表单
const resetForm = () => {
  formData.dictCode = "";
  formData.dictLabel = "";
  formData.sortOrder = currentItems.value.length;
  formData.remark = "";
  formRef.value?.clearValidate();
};

// 添加
const handleAdd = () => {
  resetForm();
  modalTitle.value = `添加${currentTypeName.value}`;
  isEdit.value = false;
  modalVisible.value = true;
};

// 编辑
const handleEdit = (record: Dictionary) => {
  formData.dictCode = record.dictCode;
  formData.dictLabel = record.dictLabel;
  formData.sortOrder = record.sortOrder;
  formData.remark = record.remark || "";

  modalTitle.value = `编辑${currentTypeName.value}`;
  isEdit.value = true;
  editingId.value = record.id;
  modalVisible.value = true;
};

// 提交
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    submitting.value = true;

    const data: any = {
      dictType: selectedType.value,
      dictLabel: formData.dictLabel,
      sortOrder: formData.sortOrder,
      remark: formData.remark,
      status: 1,
    };

    // 编辑时需要传dictCode
    if (isEdit.value && formData.dictCode) {
      data.dictCode = formData.dictCode;
    }

    if (isEdit.value && editingId.value) {
      await updateDictionary(editingId.value, data);
      message.success("更新成功");
    } else {
      await addDictionary(data);
      message.success("添加成功");
    }

    modalVisible.value = false;
    // 清除字典缓存，确保其他页面能获取到最新数据
    clearDictionaryCache(selectedType.value as any);
    loadDictionaries();
  } catch (error: any) {
    if (error.errorFields) {
      // 表单验证错误
      return;
    }
    message.error(error.message || "操作失败");
  } finally {
    submitting.value = false;
  }
};

// 删除
const handleDelete = (record: Dictionary) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除字典项"${record.dictLabel}"吗？删除后无法恢复。`,
    okText: "确定",
    cancelText: "取消",
    okType: "danger",
    onOk: async () => {
      try {
        await deleteDictionary(record.id);
        message.success("删除成功");
        // 清除字典缓存，确保其他页面能获取到最新数据
        clearDictionaryCache(record.dictType as any);
        loadDictionaries();
      } catch (error: any) {
        message.error(error.message || "删除失败");
      }
    },
  });
};

// 状态切换
const handleStatusChange = async (record: Dictionary, checked: boolean) => {
  try {
    await updateDictionary(record.id, {
      status: checked ? 1 : 0,
    });
    message.success("状态更新成功");
    // 清除字典缓存，确保其他页面能获取到最新数据
    clearDictionaryCache(record.dictType as any);
    loadDictionaries();
  } catch (error: any) {
    message.error(error.message || "状态更新失败");
  }
};

onMounted(() => {
  loadDictionaries();
});
</script>

<style scoped>
.dictionary-manage-page {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 固定头部 */
.page-header-fixed {
  flex-shrink: 0;
  /* padding: 24px; */
  background: #fff;
  /* border-bottom: 1px solid var(--border-color); */
}

.header-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.subtitle {
  display: block;
  margin-top: 8px;
  font-size: 14px;
  color: var(--text-secondary);
}

/* 内容区域 */
.page-content {
  flex: 1;
  overflow: auto;
  padding: 24px;
}

.dictionary-container {
  display: flex;
  gap: 24px;
  height: 100%;
  min-height: 600px;
}

/* 左侧类型面板 */
.dict-types-panel {
  width: 280px;
  flex-shrink: 0;
  background: #fff;
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
  overflow: hidden;
}

.panel-title {
  padding: 16px 20px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  border-bottom: 1px solid var(--border-color);
}

.type-list {
  padding: 12px;
}

.type-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  margin-bottom: 8px;
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all var(--transition-base);
  border: 1.5px solid transparent;
}

.type-item:hover {
  background: var(--primary-light);
  border-color: var(--primary-color);
}

.type-item.active {
  background: var(--primary-color);
  border-color: var(--primary-color);
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3);
}

.type-icon {
  font-size: 20px;
  color: var(--text-secondary);
}

.type-item.active .type-icon {
  color: #fff;
}

.type-info {
  flex: 1;
}

.type-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

.type-item.active .type-name {
  color: #fff;
}

.type-count {
  font-size: 12px;
  color: var(--text-tertiary);
  margin-top: 2px;
}

.type-item.active .type-count {
  color: rgba(255, 255, 255, 0.8);
}

/* 右侧内容面板 */
.dict-items-panel {
  flex: 1;
  background: #fff;
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
  display: flex;
  flex-direction: column;
}

.items-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border-color);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.dict-items-panel :deep(.ant-table-wrapper) {
  flex: 1;
  padding: 24px;
}

.label-text {
  font-weight: 500;
}

/* 表单提示 */
.form-tip {
  margin-top: 4px;
  font-size: 12px;
  color: var(--text-tertiary);
}
</style>
